<template>
	<view>
		<view class="text-blue" v-show="!state" @tap="getValidate">发送验证码</view>
		<view class="text-grey" v-show="state">{{ currentTime }}s</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			state: false, //是否开启倒计时
			totalTime: 60, //总时间，单位秒
			recordingTime: 0, //记录时间变量
			currentTime: 0 //显示时间变量
		};
	},
	name: 'verfication-code',
	props: {
		email: {
			//邮箱
			type: String,
			default: ''
		},
		mobile: {
			//手机号
			type: String,
			default: ''
		},
		type: {
			//类别
			type: String,
			default: ''
		}
	},
	methods: {
		//开始冻结发送验证码按钮
		startFreezeTime() {
			this.currentTime = this.totalTime;
			this.state = true;
			this.freezeTime();
		},
		//发送验证码
		getValidate() {
			let param = null,
				cookie = false,
				url = '';
			let tmptype = this.type.toLowerCase();

			if (tmptype == 'register') {
				url = 'userVerifyCode/register';
				cookie = false;
				param = {
					mobilePrefix: '+86',
					mobile: this.mobile
				};
			} 
			else if (tmptype == 'login') {
				url = 'userVerifyCode/login';
				cookie = false;
				param = {
					mobilePrefix: '+86',
					mobile: this.mobile
				};
			}
			else if (tmptype == 'resetpassword') {
				url = 'userVerifyCode/resetPassword';
				cookie = false;
				param = {
					mobilePrefix: '+86',
					mobile: this.mobile
				};
			}
			else if (tmptype == 'resetpaypassword') {
				url = 'userVerifyCode/resetPayPassword';
				cookie = true;
			}
			this.$http.httpRequest(url, param, cookie).then(res => {
				//console.log(url, res);
				if (res._tranStatus) {
					this.startFreezeTime(); //冻结验证码发送
					this.$util.msg('验证码已发送');
				} else {
					this.$util.msg(res._exceptionLocalizedMessage);
				}
			});
		},
		//显示冻结倒计时
		freezeTime() {
			let that = this;
			//判断是否开启
			if (this.state) {
				//判断显示时间是否已到0，判断记录时间是否已到总时间
				if (this.currentTime > 1 && this.recordingTime <= this.totalTime) {
					//记录时间增加 1
					this.recordingTime = this.recordingTime + 1;
					//显示时间，用总时间 - 记录时间
					this.currentTime = this.totalTime - this.recordingTime;
					//1秒钟后，再次执行本方法
					setTimeout(() => {
						//定时器内，this指向外部，找不到vue的方法，所以，需要用that变量。
						that.freezeTime();
					}, 1000);
				} else {
					//时间已完成，还原相关变量
					this.state = false; //关闭倒计时
					this.recordingTime = 0; //记录时间为0
					this.currentTime = this.totalTime; //显示时间为总时间
				}
			} else {
				//倒计时未开启，初始化默认变量
				this.state = false;
				this.recordingTime = 0;
				this.currentTime = this.totalTime;
			}
		}
	}
};
</script>
